import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.HashMap;

public class UdpServe {
    private HashMap<String,String> dic = new HashMap<String,String>();
    private DatagramSocket socket= null;
    public UdpServe(int port) throws SocketException {
        socket = new DatagramSocket(port);
        //创建词典，实际应用的话，数据要比这些多的多
        dic.put("hello","你好");
        dic.put("world","世界");
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true){
            //创建数据缓存区，准备接收数据
            DatagramPacket resquestpacket = new DatagramPacket(new byte[1024],1024);
            //接收数据，将数据存入缓存区
            socket.receive(resquestpacket);
            //将数据转化为字符串
            String request = new String(resquestpacket.getData(),0, resquestpacket.getLength());
            //对内容进行处理
            String newrequest = process(request);
            //创建数据缓存区，准备发送处理后的数据
            DatagramPacket response = new DatagramPacket(newrequest.getBytes(),
                    newrequest.getBytes().length,resquestpacket.getSocketAddress());
            //发送数据
            socket.send(response);
            //打印相关内容
            System.out.printf("[%s:%d] req:%s,resq:%s\n",resquestpacket.getAddress().toString(),resquestpacket.getPort()
            ,resquestpacket,response);
        }
    }

    private String process(String request) {
        return dic.getOrDefault(request,"未找到单词");
    }

    public static void main(String[] args) throws IOException {
        UdpServe serve = new UdpServe(9090);
        serve.start();
    }
}
